package View;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;


//import javax.imageio.ImageIO;
import javax.swing.*;

import Controller.Control;
import Model.Manageperson;
import Model.Person;

//import View.BaseInterface.Bouton1Listener;
/**Class qui gére toute la fenêtre et les gestions boutons
 * */

public class Window {
	private JFrame mainwindows;
	private JPanel contact;
	private JPanel displayacontact;
	private JPanel addacontact;

	private JTextArea Firstname;
	private JTextArea Lastname;
	private JTextArea Homeaddress;
	private JTextArea Companyaddress;
	private JTextArea Phonemobile;
	private JTextArea Phonehome;
	private JTextArea Homepage;
	private JTextArea EmailPro;
	private JTextArea EmailPerso;
	private JTextArea Fblink;
	private JTextArea Photo;

	private JTextArea Firstname1;
	private JTextArea Lastname1;
	private JTextArea Homeaddress1;
	private JTextArea Companyaddress1;
	private JTextArea Phonemobile1;
	private JTextArea Phonehome1;
	private JTextArea Homepage1;
	private JTextArea EmailPro1;
	private JTextArea EmailPerso1;
	private JTextArea Fblink1;
	private JTextArea Photo1;

	private JScrollPane scrollPane1;
	private JScrollPane scrollPane2;
	private JScrollPane scrollPane3;
	private JScrollPane scrollPane4;
	private JScrollPane scrollPane5;
	private JScrollPane scrollPane6;
	private JScrollPane scrollPane7;
	private JScrollPane scrollPane8;
	private JScrollPane scrollPane9;
	private JScrollPane scrollPane10;
	private JScrollPane scrollPane11;

	private JScrollPane scrollPane12;
	private JScrollPane scrollPane13;
	private JScrollPane scrollPane14;
	private JScrollPane scrollPane15;
	private JScrollPane scrollPane16;
	private JScrollPane scrollPane17;
	private JScrollPane scrollPane18;
	private JScrollPane scrollPane19;
	private JScrollPane scrollPane20;
	private JScrollPane scrollPane21;
	private JScrollPane scrollPane22;

	private JButton addaperson;
	private JButton changetheperson;
	private JButton deletetheperson;
	private JButton bouton_homepage;
	private JButton bouton_emailpro;
	private JButton bouton_emailperso;
	private JButton bouton_fbpage;

	private JComboBox combo;
	private JComboBox combo1;
	private JComboBox combo_group_show;
	private JComboBox combo_group_add;
	private Manageperson mp;
	//private JEditorPane hello;
	private String group = "Friend";
	private String d;
	private String f;
	/*private String[] tab1;
	private StringBuilder htmlBuilder;
	private int compteur = 1;*/
	private static Person p_afficher;
	private File monfichier;
	private String pathfichier; 
	private JLabel img;
	private String passagee;
	private String surn, lasn;
	private Control c=new Control();
	//private String groupp;

	

	private static ArrayList<Person> allperson;

/**Dénition de la fenêtre globale et du premier panel de gauche affichant les contacts
 * */
	public Window(ArrayList<Person> allpersone) 
	{
		mp = new Manageperson();
		mainwindows = new JFrame();
		contact = new JPanel();
		displayacontact = new JPanel();
		addacontact = new JPanel();
        
		mainwindows.setTitle("Adress book");
		mainwindows.setSize(800, 800);
		mainwindows.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainwindows.setLocationRelativeTo(null);
		mainwindows.setLayout(new GridLayout(0, 3));

		contact.setBackground(Color.ORANGE);
		displayacontact.setBackground(Color.BLUE);
		addacontact.setBackground(Color.RED);

		mainwindows.getContentPane().add(contact);
		mainwindows.getContentPane().add(displayacontact);
		mainwindows.getContentPane().add(addacontact);
		mainwindows.setVisible(true);
	
		allperson = allpersone;

		String[] tab = { "Alphabetic order", "Virtual group", "Oldest entered" };

		combo = new JComboBox(tab);

			 combo1 = new JComboBox();
			 
			 Contact_display();


				combo.setPreferredSize(new Dimension(100, 20));
				combo1.setPreferredSize(new Dimension(100, 20));
		
				contact.add(combo);
				contact.add(combo1);
				combo1.addItemListener(new ItemState1());
				mainwindows.getContentPane().add(contact);
				mainwindows.setVisible(true);
		}

	/** Fenêtre qui met à jour la jcombobox comprenant l'ensemble des noms dans le panel de gauche
	 * */

	public void Contact_display() 
	{
		
		combo1.removeAllItems();
		
	
		 combo1.revalidate();
		 combo1.repaint();
		 int value;
		 value=0;

		for (Person tp : allperson) 
		{   passagee=null;
			d = tp.getFirstname();
			f = tp.getLastname();
			passagee=d + " " + f;

			System.out.println("person "+passagee);
			combo1.insertItemAt(passagee, value);  
			value++;
			
		}

	
		 combo1.revalidate();
		 combo1.repaint();
	

		
	}
	
	/**Déclaration du panel du milieu qui affiche le contact selectionné
	 * */


	public void show_the_contact()
	{
		Firstname = new JTextArea("Firstname");
		scrollPane1 = new JScrollPane(Firstname);
		scrollPane1.setPreferredSize(new Dimension(150, 30));

		Lastname = new JTextArea("Lastname");
		scrollPane2 = new JScrollPane(Lastname);
		scrollPane2.setPreferredSize(new Dimension(150, 30));

		Homeaddress = new JTextArea("Homeaddress");
		scrollPane3 = new JScrollPane(Homeaddress);
		scrollPane3.setPreferredSize(new Dimension(150, 30));

		Companyaddress = new JTextArea("Companyaddress");
		scrollPane4 = new JScrollPane(Companyaddress);
		scrollPane4.setPreferredSize(new Dimension(150, 30));

		Phonemobile = new JTextArea("Phonemobile");
		scrollPane5 = new JScrollPane(Phonemobile);
		scrollPane5.setPreferredSize(new Dimension(150, 30));

		Phonehome = new JTextArea("Phonehome");
		scrollPane6 = new JScrollPane(Phonehome);
		scrollPane6.setPreferredSize(new Dimension(150, 30));

		Homepage = new JTextArea("Homepage");
		
		Homepage.setText("Homepage");
		scrollPane7 = new JScrollPane(Homepage);
		scrollPane7.setPreferredSize(new Dimension(150, 30));
		
		bouton_homepage=new JButton("See the homepage");
		bouton_homepage.addActionListener(new BoutonhomepagedisplayListener());
	
		EmailPro = new JTextArea("EmailPro");
		scrollPane8 = new JScrollPane(EmailPro);
		scrollPane8.setPreferredSize(new Dimension(150, 30));
		
		bouton_emailpro=new JButton("Send an pro email");
		bouton_emailpro.addActionListener(new BoutonemailprodisplayListener());
		

		EmailPerso = new JTextArea("EmailPerso");
		scrollPane9 = new JScrollPane(EmailPerso);
		scrollPane9.setPreferredSize(new Dimension(150, 30));
		bouton_emailperso=new JButton("Send an perso email");
		bouton_emailperso.addActionListener(new BoutonemailpersodisplayListener());

		Fblink = new JTextArea("Fblink");
		scrollPane10 = new JScrollPane(Fblink);
		scrollPane10.setPreferredSize(new Dimension(150, 30));
		bouton_fbpage=new JButton("See facebook page");
		bouton_fbpage.addActionListener(new BoutonfbpagedisplayListener());
		

		Photo = new JTextArea("Photo");
		scrollPane11 = new JScrollPane(Photo);
		scrollPane11.setPreferredSize(new Dimension(150, 30));

		combo_group_show = new JComboBox();
		String[] tab = { "Friend", "Family", "Work" };
		combo_group_show = new JComboBox(tab);
		combo_group_show.addItemListener(new ItemState());

		combo_group_show.setPreferredSize(new Dimension(150, 30));

		changetheperson = new JButton("Change");
		changetheperson.addActionListener(new BoutonchangepersonListener());

		deletetheperson = new JButton("Delete");
		deletetheperson.addActionListener(new BoutondeletepersonListener());
		
		monfichier=new File("inconnu.jpg");
	    pathfichier=monfichier.getAbsolutePath(); 
		img = new JLabel(new ImageIcon(pathfichier));
		
	       

		displayacontact.add(scrollPane1);
		displayacontact.add(scrollPane2);
		displayacontact.add(scrollPane3);
		displayacontact.add(scrollPane4);
		displayacontact.add(scrollPane5);
		displayacontact.add(scrollPane6);
		displayacontact.add(scrollPane7);
		displayacontact.add(bouton_homepage);
		displayacontact.add(scrollPane8);
		displayacontact.add(bouton_emailpro);
		displayacontact.add(scrollPane9);
		displayacontact.add(bouton_emailperso);
		displayacontact.add(scrollPane10);
		displayacontact.add(bouton_fbpage);
		displayacontact.add(scrollPane11);
		displayacontact.add(combo_group_show);
		displayacontact.add(changetheperson);
		displayacontact.add(deletetheperson);
		displayacontact.add(img);
		

		mainwindows.getContentPane().add(displayacontact);
		mainwindows.setVisible(true);

	}
/**Déclaration du panel de droite qui permet d'ajouter un contact
 * **/
	public void add_someone_display() 
	{

		Firstname1 = new JTextArea("Firstname");
		scrollPane12 = new JScrollPane(Firstname1);
		scrollPane12.setPreferredSize(new Dimension(150, 30));

		Lastname1 = new JTextArea("Lastname");
		scrollPane13 = new JScrollPane(Lastname1);
		scrollPane13.setPreferredSize(new Dimension(150, 30));

		Homeaddress1 = new JTextArea("Homeaddress");
		scrollPane14 = new JScrollPane(Homeaddress1);
		scrollPane14.setPreferredSize(new Dimension(150, 30));

		Companyaddress1 = new JTextArea("Companyaddress");
		scrollPane15 = new JScrollPane(Companyaddress1);
		scrollPane15.setPreferredSize(new Dimension(150, 30));

		Phonemobile1 = new JTextArea("Phonemobile");
		scrollPane16 = new JScrollPane(Phonemobile1);
		scrollPane16.setPreferredSize(new Dimension(150, 30));

		Phonehome1 = new JTextArea("Phonehome");
		scrollPane17 = new JScrollPane(Phonehome1);
		scrollPane17.setPreferredSize(new Dimension(150, 30));

		Homepage1 = new JTextArea("Homepage");
		scrollPane18 = new JScrollPane(Homepage1);
		scrollPane18.setPreferredSize(new Dimension(150, 30));

		EmailPro1 = new JTextArea("EmailPro");
		scrollPane19 = new JScrollPane(EmailPro1);
		scrollPane19.setPreferredSize(new Dimension(150, 30));

		EmailPerso1 = new JTextArea("EmailPerso");
		scrollPane20 = new JScrollPane(EmailPerso1);
		scrollPane20.setPreferredSize(new Dimension(150, 30));

		Fblink1 = new JTextArea("Fblink");
		scrollPane21 = new JScrollPane(Fblink1);
		scrollPane21.setPreferredSize(new Dimension(150, 30));

		Photo1 = new JTextArea("Photo");
		scrollPane22 = new JScrollPane(Photo1);
		scrollPane22.setPreferredSize(new Dimension(150, 30));

		combo_group_add = new JComboBox();
		String[] tab = { "Friend", "Family", "Work" };
		combo_group_add = new JComboBox(tab);
		combo_group_add.addItemListener(new ItemState2());

		addaperson = new JButton("Add");
		addaperson.addActionListener(new BoutonaddpersonListener());

		addacontact.add(scrollPane12);
		addacontact.add(scrollPane13);
		addacontact.add(scrollPane14);
		addacontact.add(scrollPane15);
		addacontact.add(scrollPane16);
		addacontact.add(scrollPane17);
		addacontact.add(scrollPane18);
		addacontact.add(scrollPane19);
		addacontact.add(scrollPane20);
		addacontact.add(scrollPane21);
		addacontact.add(scrollPane22);
		addacontact.add(combo_group_add);
		addacontact.add(addaperson);

		mainwindows.getContentPane().add(addacontact);
		mainwindows.setVisible(true);
	}
/**Listener du bouton add qui permet d'ajouter le bouton dans le fichier appel de la classe manageperson
 * **/
	class BoutonaddpersonListener implements ActionListener 
	{
		public void actionPerformed(ActionEvent arg0) 
		{

			String Firstn = Firstname1.getText();
			String Lastn = Lastname1.getText();
			String Homea = Homeaddress1.getText();
			String Companya = Companyaddress1.getText();
			String Phonem = Phonemobile1.getText();
			String Phoneh = Phonehome1.getText();
			String Homep = Homepage1.getText();
			String EmailPr = EmailPro1.getText();
			String EmailPer = EmailPerso1.getText();
			String Fb = Fblink1.getText();
			String photo = Photo1.getText();
			String photo_dup="copie_"+photo;
			/*File n1=new File(photo);
			File n2=new File(photo);*/
			
			 //mp.duplication_picture(new File(photo),new File(photo_dup));
			
			c.dup_photo(photo,photo_dup,mp);
			
			 
			Person p = new Person(Firstn, Lastn, Homea, Companya, Phonem,
					Phoneh, Homep, EmailPr, EmailPer, Fb, photo_dup, group);
			System.out.println("person add"+Firstn);
			// l'ajout dans le fichier ou dans l'arraylist
			//mp.addperson(p);
			allperson.add(p);
			
			c.write_in_the_file(allperson,mp);
			//mp.write_file(allperson);
			

			System.out.println("person add");
			//combo1.removeAllItems();
			Contact_display() ;
		}

	}
	/**Bouton qui permet d'enregistrer les valeurs changeantes d'un individu
	 * en realité elle supprime l'individu et en crée un nouveau
	 * */

	class BoutonchangepersonListener implements ActionListener 
	{
		public void actionPerformed(ActionEvent arg0) 
		{   String group_temp=p_afficher.getGroup();
		  String photo_temp=p_afficher.getPhoto();
	
			allperson.remove(p_afficher);
			p_afficher = null;

			String Firstn = Firstname.getText();
			String Lastn = Lastname.getText();
			String Homea = Homeaddress.getText();
			String Companya = Companyaddress.getText();
			String Phonem = Phonemobile.getText();
			String Phoneh = Phonehome.getText();
			String Homep = Homepage.getText();
			String EmailPr = EmailPro.getText();
			String EmailPer = EmailPerso.getText();
			String Fb = Fblink.getText();
			String photo = Photo.getText();
		
			
			if (photo_temp.compareTo(photo)==0)
			{System.out.println("comparaison differente");
		   String photo1="copie_"+photo;
			
		   c.dup_photo(photo,photo1,mp);
			mp.duplication_picture(new File(photo),new File(photo1));
			}
			
			if (group==null)
			{
				group=group_temp;
				System.out.println("mon groupe est"+group);
			}

			p_afficher = new Person(Firstn, Lastn, Homea, Companya, Phonem,
					Phoneh, Homep, EmailPr, EmailPer, Fb, photo, group);
			
			allperson.add(p_afficher);
			c.write_in_the_file(allperson,mp);
			//mp.write_file(allperson);
		
			Contact_display();
			
			System.out.println("personne modifié");

		}

	

		
	}
	/**Permet d'ouvrir l'homepage de la personne affiché
	 * */

	class BoutonhomepagedisplayListener implements ActionListener
	  {
	  	public void actionPerformed(ActionEvent arg0) 
	  	{
	  	Desktop desktop = null;
	  	java.net.URI url;
		  	try 
		  	{
		  	url = new java.net.URI(p_afficher.getHomepage());
				  	if (Desktop.isDesktopSupported())
				  	{
				  	desktop = Desktop.getDesktop();
				  	desktop.browse(url);
				  	}
		  	}
		  	catch (Exception ex) 
		  	{
		  	System.out.println(ex.getMessage());
		  	}
	  		
	  	}
	  
	  }
	
	/**Permet d'ouvrir outlook ou similaire en ajoutant l'adresse mail
	 * **/
	  class BoutonemailprodisplayListener implements ActionListener 
	  {
	  	public void actionPerformed(ActionEvent arg0) 
	  	{
	  	  String mailTo = "";
	        URI uriMailTo = null;

	        //Assembler l'url
	        mailTo = p_afficher.getEmailPro();
	        mailTo += "?subject=Test avec Java";
	        //mailTo += "?body=Envoyer un email avec Java";

	        //Ouvrir le logiciel de messagerie par défaut
	        if (Desktop.isDesktopSupported()) 
	        {
	            if (Desktop.getDesktop().isSupported(Desktop.Action.MAIL)) 
	            {
	                try {
	                    uriMailTo = new URI("mailto", mailTo, null);
	                    Desktop.getDesktop().mail(uriMailTo);
	                } 
	                catch (IOException ex) 
	                {
	                   // Logger.getLogger(DefaultSendMail.class.getName()).log(Level.SEVERE, null, ex);
	                }
	                catch (URISyntaxException ex)
	                {
	                    //Logger.getLogger(DefaultSendMail.class.getName()).log(Level.SEVERE, null, ex);
	                }
	                }}
	  	}
	  	
	  }
	  
	  /**Permet d'ouvrir outlook ou similaire et d'y insérer l'adresse mail choisie
	   * **/
	  
	  
	  class BoutonemailpersodisplayListener implements ActionListener 
	  {
	  	public void actionPerformed(ActionEvent arg0) 
	  	{
	  		String mailTo = "";
	        URI uriMailTo = null;

	        //Assembler l'url
	        mailTo = p_afficher.getEmailPerso();
	        mailTo += "?subject=Test avec Java";
	        //mailTo += "?body=Envoyer un email avec Java";

	        //Ouvrir le logiciel de messagerie par défaut
	        if (Desktop.isDesktopSupported()) 
	        {
	            if (Desktop.getDesktop().isSupported(Desktop.Action.MAIL)) 
	            {
	                try {
	                    uriMailTo = new URI("mailto", mailTo, null);
	                    Desktop.getDesktop().mail(uriMailTo);
	                } 
	                catch (IOException ex) 
	                {
	                   // Logger.getLogger(DefaultSendMail.class.getName()).log(Level.SEVERE, null, ex);
	                }
	                catch (URISyntaxException ex)
	                {
	                    //Logger.getLogger(DefaultSendMail.class.getName()).log(Level.SEVERE, null, ex);
	                }
	                }}
	  		
	  	}
	  	
	  }
	  
	  /**Permet d'ouvrir la page fb de cla personne en cours
	   * **/
	  class BoutonfbpagedisplayListener implements ActionListener  
	  {
		  	public void actionPerformed(ActionEvent arg0) 
		  	{	Desktop desktop = null;
	  	java.net.URI url;
		  	try 
		  	{
		  	url = new java.net.URI(p_afficher.getFblink());
				  	if (Desktop.isDesktopSupported())
				  	{
				  	desktop = Desktop.getDesktop();
				  	desktop.browse(url);
				  	}
		  	}
		  	catch (Exception ex) 
		  	{
		  	System.out.println(ex.getMessage());
		  	}
		  		
		  	}
		  	
     }
	
	  /**Supprime en mémoire et sur l'adresse book la personne selectionné
	   * **/
  class BoutondeletepersonListener implements ActionListener 
{
	public void actionPerformed(ActionEvent arg0) 
	{
		System.out.println("je suis ds la boucle");

		
		  allperson.remove(p_afficher); 
		  mp.write_file(allperson);
		  //revoir
		  //combo1.removeAllItems();
		  Contact_display();
		  //show_the_contact();
		  //add_someone_display();
		 
		System.out.println("personne supprimé");

	}



}
  /**Enregistre le listener de la combobox lors du changement d'une personne
   * **/

class ItemState implements ItemListener 
{
	public void itemStateChanged(ItemEvent e) 
	{
		group=(String) e.getItem();
	}
}
/**Lorsqu'on choisit une personne dans la combobox ça l'affiche
 * */

class ItemState1 implements ItemListener 
{
	public void itemStateChanged(ItemEvent e) 
	{   String Person;
		Person = (String) e.getItem();
		String[] tab3 = Person.split(" ");
		surn = tab3[0];
		lasn = tab3[1];
		System.out.println("chaine" + Person);
		System.out.println("sr " + surn + " ln" + lasn);
		p_afficher=new Person();

		for (Person tp : allperson) 
		{

			if (surn.equals(tp.getFirstname()) && lasn.equals(tp.getLastname())) 
			{System.out.println("trouve "+tp.getFirstname());
				p_afficher = tp;
			}
		}
 //System.out.println(""+p_afficher.getFirstname());
		
		Firstname.setText(p_afficher.getFirstname());
		Lastname.setText(p_afficher.getLastname());
		Homeaddress.setText(p_afficher.getHomeaddress());
		Companyaddress.setText(p_afficher.getCompanyaddress());
		Phonemobile.setText(p_afficher.getPhonemobile());
		Phonehome.setText(p_afficher.getPhonehome());
		Homepage.setText(p_afficher.getHomepage());
		EmailPro.setText(p_afficher.getEmailPro());
		EmailPerso.setText(p_afficher.getEmailPerso());
		Fblink.setText(p_afficher.getFblink());
		Photo.setText(p_afficher.getPhoto());
		
		//groupp=p_afficher.getGroup();
		System.out.println("mon group est"+group);
		
	
		System.out.println(""+p_afficher.getPhoto());
		if (p_afficher.getPhoto()==null)
			img.setIcon(new ImageIcon("inconnu.jpg"));
		else
		img.setIcon(new ImageIcon(p_afficher.getPhoto()));
		
	
		
		
		     
		       

	
		
	}
	}
/**Enregistre l'élément de la combobox de droite lors de l'ajout d'une personne
 * **/

class ItemState2 implements ItemListener 
{
	public void itemStateChanged(ItemEvent e) 
	{
		group=(String) e.getItem();
	}
}

}
